package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/Task", "/task", "/TaskServlet", "/taskServlet" }, initParams = {
        @WebInitParam(name = "mode", value = "") })
public class TaskServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public TaskServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<TaskModel>checkInsertRight()) {

				// TODO : MORE CODE HERE

                getServletContext().getRequestDispatcher("/taskNew.jsp").forward(request, response);
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

                TaskModel query = new TaskModel();				
                String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));


				GenericDal<TaskModel, TaskModelExt> dal = new GenericDal<TaskModel, TaskModelExt>(
						new TaskModel());

				TaskModel obj = null;
				try {
					obj = dal.select(query);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (obj != null) {

					// TODO : MORE CODE HERE

                    request.setAttribute("task", obj);
                    getServletContext().getRequestDispatcher("/taskEdit.jsp").forward(request, response);

				} else {
					// TODO : data not found
				}			
		} else if (mode.equalsIgnoreCase("view")) {
			
                TaskModel query = new TaskModel();				
                String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));


				GenericDal<TaskModel, TaskModelExt> dal = new GenericDal<TaskModel, TaskModelExt>(
						new TaskModel());

				TaskModel obj = null;
				try {
					obj = dal.select(query);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (obj != null) {
					// TODO : LOAD MASTER DATA HERE
					// It's specific code that cannot be generated

                    request.setAttribute("task", obj);
                    getServletContext().getRequestDispatcher("/taskView.jsp").forward(request, response);

				} else {
					// TODO : data not found
				}			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("insert")) {
			
				TaskModel obj = new TaskModel();

                String name = request.getParameter("name");
					obj.setName(name);

String code = request.getParameter("code");
					obj.setCode(code);

String description = request.getParameter("description");
					obj.setDescription(description);

String id_employee = request.getParameter("id_employee");
                    if (id_employee != null && !id_employee.isEmpty()) {
					    obj.setIdEmployee(Integer.parseInt(id_employee));
                    }

String id_type = request.getParameter("id_type");
                    if (id_type != null && !id_type.isEmpty()) {
					    obj.setIdType(Integer.parseInt(id_type));
                    }

String id_phase = request.getParameter("id_phase");
                    if (id_phase != null && !id_phase.isEmpty()) {
					    obj.setIdPhase(Integer.parseInt(id_phase));
                    }

String status = request.getParameter("status");
                    if (status != null && !status.isEmpty()) {
					    obj.setStatus(Integer.parseInt(status));
                    }


    String plan_start_time_date = request.getParameter("plan_start_time_date");
    String plan_start_time_time = request.getParameter("plan_start_time_time");
     if (plan_start_time_date != null && !plan_start_time_date.isEmpty())
     {
		if (plan_start_time_time != null && !plan_start_time_time.isEmpty()) 
		{
			obj.setPlanStartTime(DateTimeUtil.parseDateTime(plan_start_time_date,	plan_start_time_time));
		} 
		else 
		{
			obj.setPlanStartTime(DateTimeUtil.parseDate(plan_start_time_date));
		}
	}


    String plan_end_time_date = request.getParameter("plan_end_time_date");
    String plan_end_time_time = request.getParameter("plan_end_time_time");
     if (plan_end_time_date != null && !plan_end_time_date.isEmpty())
     {
		if (plan_end_time_time != null && !plan_end_time_time.isEmpty()) 
		{
			obj.setPlanEndTime(DateTimeUtil.parseDateTime(plan_end_time_date,	plan_end_time_time));
		} 
		else 
		{
			obj.setPlanEndTime(DateTimeUtil.parseDate(plan_end_time_date));
		}
	}


    String real_start_tate_date = request.getParameter("real_start_tate_date");
    String real_start_tate_time = request.getParameter("real_start_tate_time");
     if (real_start_tate_date != null && !real_start_tate_date.isEmpty())
     {
		if (real_start_tate_time != null && !real_start_tate_time.isEmpty()) 
		{
			obj.setRealStartTate(DateTimeUtil.parseDateTime(real_start_tate_date,	real_start_tate_time));
		} 
		else 
		{
			obj.setRealStartTate(DateTimeUtil.parseDate(real_start_tate_date));
		}
	}


    String real_end_time_date = request.getParameter("real_end_time_date");
    String real_end_time_time = request.getParameter("real_end_time_time");
     if (real_end_time_date != null && !real_end_time_date.isEmpty())
     {
		if (real_end_time_time != null && !real_end_time_time.isEmpty()) 
		{
			obj.setRealEndTime(DateTimeUtil.parseDateTime(real_end_time_date,	real_end_time_time));
		} 
		else 
		{
			obj.setRealEndTime(DateTimeUtil.parseDate(real_end_time_date));
		}
	}

String need_approval = request.getParameter("need_approval");
					obj.setNeedApproval(need_approval.equalsIgnoreCase("true")
							|| need_approval.equalsIgnoreCase("1"));

String is_event = request.getParameter("is_event");
					obj.setIsEvent(is_event.equalsIgnoreCase("true")
							|| is_event.equalsIgnoreCase("1"));

String is_draft = request.getParameter("is_draft");
					obj.setIsDraft(is_draft.equalsIgnoreCase("true")
							|| is_draft.equalsIgnoreCase("1"));

String notification = request.getParameter("notification");
                    if (notification != null && !notification.isEmpty()) {
					    obj.setNotification(Integer.parseInt(notification));
                    }



String rate = request.getParameter("rate");
                    if (rate != null && !rate.isEmpty()) {
					    obj.setRate(Integer.parseInt(rate));
                    }

				

                obj.setCreator(SessionUtil.getCurrentUserID());

				if (CommonBll.checkInputs(obj)) {
					GenericDal<TaskModel, TaskModelExt> dal = new GenericDal<TaskModel, TaskModelExt>(
							new TaskModel());

					int res = 0;
					try {
						res = dal.insert(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res > 0) {
						// TODO : success, redirect to somewhere
					} else {
						// TODO : processing error here
					}
				} else {

					// invalid input

                    request.setAttribute("task", obj);
                    getServletContext().getRequestDispatcher("/taskInput.jsp").forward(request, response);

				}		
		} else if (mode.equalsIgnoreCase("update")) {		

                TaskModel query = new TaskModel();				
                String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));


				GenericDal<TaskModel, TaskModelExt> dal = new GenericDal<TaskModel, TaskModelExt>(
						new TaskModel());

				TaskModel obj = null;
				try {
					obj = dal.select(query);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (obj != null) {

                    String name = request.getParameter("name");
					obj.setName(name);

String code = request.getParameter("code");
					obj.setCode(code);

String description = request.getParameter("description");
					obj.setDescription(description);


					String id_employee = request.getParameter("id_employee");
					obj.setIdEmployee(Integer.parseInt(id_employee));


					String id_type = request.getParameter("id_type");
					obj.setIdType(Integer.parseInt(id_type));


					String id_phase = request.getParameter("id_phase");
					obj.setIdPhase(Integer.parseInt(id_phase));


					String status = request.getParameter("status");
					obj.setStatus(Integer.parseInt(status));

String plan_start_time_date = request.getParameter("plan_start_time_date");
					String plan_start_time_time = request.getParameter("plan_start_time_time");
        obj.setPlanStartTime(DateTimeUtil.parseDateTime(plan_start_time_date, plan_start_time_time));

String plan_end_time_date = request.getParameter("plan_end_time_date");
					String plan_end_time_time = request.getParameter("plan_end_time_time");
        obj.setPlanEndTime(DateTimeUtil.parseDateTime(plan_end_time_date, plan_end_time_time));

String real_start_tate_date = request.getParameter("real_start_tate_date");
					String real_start_tate_time = request.getParameter("real_start_tate_time");
        obj.setRealStartTate(DateTimeUtil.parseDateTime(real_start_tate_date, real_start_tate_time));

String real_end_time_date = request.getParameter("real_end_time_date");
					String real_end_time_time = request.getParameter("real_end_time_time");
        obj.setRealEndTime(DateTimeUtil.parseDateTime(real_end_time_date, real_end_time_time));

String need_approval = request.getParameter("need_approval");
					obj.setNeedApproval(need_approval.equalsIgnoreCase("true")
							|| need_approval.equalsIgnoreCase("1"));

String is_event = request.getParameter("is_event");
					obj.setIsEvent(is_event.equalsIgnoreCase("true")
							|| is_event.equalsIgnoreCase("1"));

String is_draft = request.getParameter("is_draft");
					obj.setIsDraft(is_draft.equalsIgnoreCase("true")
							|| is_draft.equalsIgnoreCase("1"));


					String notification = request.getParameter("notification");
					obj.setNotification(Integer.parseInt(notification));




					String rate = request.getParameter("rate");
					obj.setRate(Integer.parseInt(rate));

				

                    if (CommonBll.checkInputs(obj)) {	

					    int res = Integer.MIN_VALUE;
					    try {
						    res = dal.update(obj);
					    } catch (SQLException e) {
						    // TODO Auto-generated catch block
						    e.printStackTrace();
					    } catch (ClassNotFoundException e) {
						    // TODO Auto-generated catch block
						    e.printStackTrace();
					    }

					    if (res == 0) {
						    // TODO success
					    } else {
						    // TODO error
					    }
                    } else {
					request.setAttribute("task", obj);
					getServletContext().getRequestDispatcher("/taskEdit.jsp").forward(request, response);
				    }
				} else {
					// TODO data not found
				}			
		} else if (mode.equalsIgnoreCase("delete")) {		

                TaskModel query = new TaskModel();				
                String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));


				GenericDal<TaskModel, TaskModelExt> dal = new GenericDal<TaskModel, TaskModelExt>(
						new TaskModel());

				int res = Integer.MIN_VALUE;
				try {
					res = dal.delete(query);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res == 0) {
					// TODO success
				} else {
					// TODO fail
				}			
		}
	}

}